package cn.xmallmanager.controllers;

import cn.xmallmanager.commons.models.PageQueryResult;
import cn.xmallmanager.commons.models.RequestResult;
import cn.xmallmanager.models.ItemParam;
import cn.xmallmanager.services.ItemParamService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * Created by MoTaiXian on 2017/7/12.
 */

@Controller
@RequestMapping("/item_param")
public class ItemParamController {
    private static final Logger logger = LoggerFactory.getLogger(ItemParamController.class);
    @Autowired
    ItemParamService itemParamService;

    @GetMapping
    @RequestMapping("/query/itemcatid/{itemCatId}")
    @ResponseBody
    public RequestResult getItemParamByCid(@PathVariable Long itemCatId) {
        RequestResult result=null;
        ItemParam itemParam= itemParamService.getByCatId(itemCatId);
        if (itemParam!=null){
            return RequestResult.ok("success",itemParam);
        }


        return RequestResult.error("fail to query "+String.valueOf(itemCatId));
    }

    @PostMapping("/save/{cid}")
    @ResponseBody
    public RequestResult saveItemParam(@PathVariable Long cid, String paramData) throws Exception {
        logger.debug("cid={},paramData={}",cid,paramData);

        ItemParam itemParam=itemParamService.getByCatId(cid);
        if(itemParam!=null) return RequestResult.error("商品规格已存在");

        itemParam=new ItemParam();
        itemParam.setItemCatId(cid);
        itemParam.setParamData(paramData);
        itemParam.setCreated(new Date());
        itemParam.setUpdated(new Date());

        itemParamService.save(itemParam);

        return  RequestResult.ok();
    }

    @GetMapping("/list")
    @ResponseBody
    public PageQueryResult getItemParamPage(@RequestParam("page") int page,@RequestParam("rows") int rows){

        return itemParamService.getItemParamsByPage(page,rows);
    }



}
